/**
 * 研发项目详情页面
 * 优化版 - 适配小驼峰命名和新数据结构
 */
const cloudHelper = require('../../../config/project_helpers_config').cloudHelper;
const pageHelper = require('../../../config/project_helpers_config').pageHelper;
const timeHelper = require('../../../config/project_helpers_config').timeHelper;
const { projectStore } = require('../../../config/path_resolver.js').getRootConfigPath('path_resolver.js').getProjectStorePath('modules/research/project_store');
const { stateStore } = require('../../../config/path_resolver.js').getRootConfigPath('path_resolver.js').getProjectStorePath('modules/research/state_store');
const { formatTime } = require('../../../config/path_resolver.js').pageHelper;
const { logEvent } = require('../../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../../helpers/network_helper.js');

Page({
  data: {
    isLoading: true,
    id: '',
    project: null,
    
    // 状态显示
    statusInfo: null,
    allowedTransitions: [],
    stateHistory: [],
    
    // 操作相关
    activeTabIndex: 0,
    showActionSheet: false,
    actions: []
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function(options) {
    const { id } = options;
    if (!id) {
      pageHelper.showModal('参数错误');
      return;
    }
    
    this.setData({ id });
    
    // 网络检测
    const net = await getNetworkStatus();
    if (!net.isConnected) {
      wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
    } else if (net.networkType === '2g') {
      wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
    }
    listenNetworkStatus((res) => {
      if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
      else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
    });
    logEvent('page_load', { page: 'plm_research_detail' });
    
    await this._loadProjectDetail();
    
    // 加载状态相关信息
    if (this.data.project) {
      await this._loadStateInfo();
    }
  },
  
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 解除状态绑定
    stateStore.clearState();
  },
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: async function() {
    await this._loadProjectDetail();
    wx.stopPullDownRefresh();
  },
  
  /**
   * 加载项目详情
   */
  _loadProjectDetail: async function() {
    this.setData({ isLoading: true });
    
    try {
      const project = await projectStore.loadProjectDetail(this.data.id);
      if (!project) {
        pageHelper.showModal('项目不存在或已删除');
        return;
      }
      
      // 处理项目数据
      const { project: processedProject, statusInfo } = this._processProjectData(project);
      
      this.setData({
        project: processedProject,
        statusInfo,
        loading: false
      });
      
      // 加载状态相关信息
      await this._loadStateInfo();
    } catch (err) {
      console.error('加载项目详情失败', err);
      pageHelper.showModal('加载失败: ' + (err.message || '未知错误'));
    } finally {
      this.setData({ isLoading: false });
    }
  },
  
  /**
   * 加载状态信息
   */
  _loadStateInfo: async function() {
    try {
      // 初始化状态管理
      await stateStore.initState(this.data.project.id);
      
      // 获取当前状态信息
      const statusInfo = stateStore.getCurrentState();
      
      // 获取允许的状态转换
      const allowedTransitions = stateStore.getAllowedTransitions();
      
      // 获取状态历史
      const stateHistory = stateStore.getFormattedHistory();
      
      this.setData({ 
        statusInfo,
        allowedTransitions,
        stateHistory
      });
    } catch (err) {
      console.error('加载状态信息失败', err);
    }
  },
  
  /**
   * 格式化项目数据用于显示
   */
  _formatProjectData: function(project) {
    if (!project) return null;
    
    // 日期格式化处理
    const formatTimeField = (timestamp, format = 'YYYY-MM-DD') => {
      return timestamp ? formatTime(timestamp * 1000, format) : '--';
    };
    
    // 客户端项目数据格式化
    return {
      ...project,
      
      // 格式化日期显示
      createTimeFormat: formatTimeField(project.createTime, 'YYYY-MM-DD HH:mm'),
      updateTimeFormat: formatTimeField(project.updateTime, 'YYYY-MM-DD HH:mm'),
      startDateFormat: formatTimeField(project.startDate),
      deadlineFormat: formatTimeField(project.deadline),
      planStartDateFormat: formatTimeField(project.planStartDate),
      planEndDateFormat: formatTimeField(project.planEndDate),
      
      // 格式化状态显示
      priorityName: this._getPriorityName(project.priority)
    };
  },
  
  /**
   * 获取优先级显示名称
   */
  _getPriorityName: function(priority) {
    const priorityMap = {
      'low': '低',
      'normal': '中',
      'high': '高',
      'urgent': '紧急'
    };
    return priorityMap[priority] || '中';
  },
  
  /**
   * 切换标签页
   */
  onTabTap: function(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({ activeTabIndex: index });
  },
  
  /**
   * 打开状态操作菜单
   */
  onStatusActionTap: function() {
    if (!this.data.allowedTransitions || this.data.allowedTransitions.length === 0) {
      pageHelper.showModal('当前状态下没有可执行的操作');
      return;
    }
    
    // 构建操作菜单
    const actions = this.data.allowedTransitions.map(transition => ({
      name: transition.name,
      eventId: transition.eventId
    }));
    
    this.setData({
      showActionSheet: true,
      actions
    });
  },
  
  /**
   * 执行状态转换
   */
  onActionTap: async function(e) {
    const { eventId } = e.currentTarget.dataset;
    
    this.setData({ showActionSheet: false });
    
    if (!eventId) return;
    
    try {
      // 显示确认对话框
      const transition = this.data.allowedTransitions.find(t => t.eventId === eventId);
      if (!transition) return;
      
      const res = await pageHelper.showConfirm(`确定要执行"${transition.name}"操作吗？`);
      if (!res) return;
      
      // 执行状态转换
      const result = await stateStore.transitState(eventId);
      
      if (result && result.success) {
        pageHelper.showSuccessToast('操作成功', 1500);
        
        // 重新加载数据
        setTimeout(() => {
          this._loadProjectDetail();
          this._loadStateInfo();
        }, 1500);
      } else {
        pageHelper.showModal(result.message || '操作失败');
      }
    } catch (err) {
      console.error('执行状态转换失败', err);
      pageHelper.showModal('操作失败: ' + (err.message || '未知错误'));
    }
  },
  
  /**
   * 关闭操作菜单
   */
  onCloseActionSheet: function() {
    this.setData({ showActionSheet: false });
  },
  
  /**
   * 编辑项目
   */
  onEditTap: function() {
    wx.navigateTo({
      url: `/projects/plm/pages/research/edit/index?id=${this.data.id}`
    });
  },
  
  /**
   * 查看图片
   */
  onImagePreview: function(e) {
    const { url, urls } = e.currentTarget.dataset;
    wx.previewImage({
      urls: urls || [url],
      current: url
    });
  },
  
  // 处理项目数据
  _processProjectData(project) {
    if (!project) return null;
    
    // 确保model字段存在
    if (!project.model) {
      project.model = '未命名项目';
    }
    
    // 确保使用fullStatusDesc
    if (!project.fullStatusDesc) {
      // 尝试使用状态工具计算状态
      try {
        project.fullStatusDesc = ResearchProjectModel.getStatusDesc(
          project.level1, project.level2, project.level3, project.level4
        );
      } catch (error) {
        console.error('计算状态描述出错:', error);
        project.fullStatusDesc = '未知状态';
      }
    }
    
    // 计算开发状态
    project.developmentStatus = statusHelper.getDevelopmentStatus(project);
    
    // 处理优先级
    project.priorityClass = this._getPriorityClass(project.priority);
    project.priorityName = this._getPriorityName(project.priority);
    
    // 处理状态
    const statusInfo = {
      statusClass: this._getStatusClass(project.level1)
    };
    
    // 处理电机控制项目特有字段 - 确保扩展字段完全一致
    if (project.projectType === '磁编' || project.projectType === '霍尔' || 
        project.projectType === '风机' || project.projectType === '水泵') {
      // 添加默认值，确保视图展示完整
      project.workTemp = project.workTemp || '--';
      project.certification = project.certification || '--';
      project.lowPower = project.lowPower || '--';
      project.startupTime = project.startupTime || '--';
      project.conformalCoating = project.conformalCoating || '--';
      project.ratedVoltage = project.ratedVoltage || '--';
      project.maxPower = project.maxPower || '--';
      project.maxSpeed = project.maxSpeed || '--';
      project.polePairs = project.polePairs || '--';
      project.hasHall = project.hasHall || '--';
      project.hasFG = project.hasFG || '--';
      project.hasBrake = project.hasBrake || '--';
      project.controlMode = project.controlMode || '--';
      project.controlAlgorithm = project.controlAlgorithm || '--';
      project.rotation = project.rotation || '--';
      project.controlInterface = project.controlInterface || '--';
      
      // 处理保护参数
      project.stallProtection = project.stallProtection || '--';
      project.overvoltageProtection = project.overvoltageProtection || '--';
      project.undervoltageProtection = project.undervoltageProtection || '--';
      project.temperatureProtection = project.temperatureProtection || '--';
      project.overcurrentProtection = project.overcurrentProtection || '--';
      project.currentLimitProtection = project.currentLimitProtection || '--';
      project.blockageProtection = project.blockageProtection || '--';
      project.phaseProtection = project.phaseProtection || '--';
      
      // 处理样机信息
      if (project.hasSample === '有') {
        project.sampleCount = project.sampleCount || '0';
        project.sampleImages = project.sampleImages || [];
      }
    }
    
    return {
      project,
      statusInfo
    };
  }
}); 